package com.formiaomiao.demain.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.formiaomiao.demain.R;
import com.formiaomiao.demain.adapter.ChatAdapter;
import com.formiaomiao.demain.adapter.CommonFragmentPagerAdapter;
import com.formiaomiao.demain.base.BaseActivity;
import com.formiaomiao.demain.base.BaseApplication;
import com.formiaomiao.demain.db.IsPushBean;
import com.formiaomiao.demain.db.MsgBean;
import com.formiaomiao.demain.fragment.ChatEmotionFragment;
import com.formiaomiao.demain.fragment.ChatFunctionFragment;
import com.formiaomiao.demain.greendao.IsPushBeanDao;
import com.formiaomiao.demain.greendao.MsgBeanDao;
import com.formiaomiao.demain.model.EventbusChatBean;
import com.formiaomiao.demain.model.FullImageInfo;
import com.formiaomiao.demain.model.MessageInfo;
import com.formiaomiao.demain.util.Constants;
import com.formiaomiao.demain.util.GlobalOnItemClickManagerUtils;
import com.formiaomiao.demain.util.MediaManager;
import com.formiaomiao.demain.util.MessageEvent;
import com.formiaomiao.demain.util.StaticValues;
import com.formiaomiao.demain.weight.EmotionInputDetector;
import com.formiaomiao.demain.weight.NoScrollViewPager;
import com.formiaomiao.demain.weight.StateButton;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.jude.easyrecyclerview.EasyRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ChatActivity extends BaseActivity {

    @BindView(R.id.iv_class_back)
    ImageView ivClassBack;
    @BindView(R.id.tv_class_name)
    TextView tvClassName;
    @BindView(R.id.tv_class_submit)
    TextView tvClassSubmit;
    @BindView(R.id.chat_list)
    EasyRecyclerView chatList;
    @BindView(R.id.emotion_voice)
    ImageView emotionVoice;
    @BindView(R.id.edit_text)
    EditText editText;
    @BindView(R.id.voice_text)
    TextView voiceText;
    @BindView(R.id.emotion_button)
    ImageView emotionButton;
    @BindView(R.id.emotion_add)
    ImageView emotionAdd;
    @BindView(R.id.emotion_send)
    StateButton emotionSend;
    @BindView(R.id.viewpager)
    NoScrollViewPager viewpager;
    @BindView(R.id.emotion_layout)
    RelativeLayout emotionLayout;
    @BindView(R.id.tiv_class_more)
    ImageView tivClassMore;
    @BindView(R.id.iv_chat)
    ImageView ivChat;

    private static ChatActivity chatActivity;

    private EmotionInputDetector mDetector;
    private ArrayList<Fragment> fragments;
    private ChatEmotionFragment chatEmotionFragment;
    private ChatFunctionFragment chatFunctionFragment;
    private CommonFragmentPagerAdapter adapter;

    private ChatAdapter chatAdapter;
    private LinearLayoutManager layoutManager;
    private List<MessageInfo> messageInfos;
    //录音相关
    int animationRes = 0;
    int res = 0;
    AnimationDrawable animationDrawable = null;
    private ImageView animView;
    private String Remarks = "";    //好友备注

    EMMessage message;

    List<EMMessage> messages;
    List<EMMessage> msglist;
    List<EventbusChatBean> eventlist;

    MsgBeanDao msgBeanDao;
    IsPushBeanDao isPushBeanDao;
    IsPushBean pushBean = new IsPushBean();
    List<MsgBean> msgBeanList = new ArrayList<>();

    EventbusChatBean eventbusChatBean = new EventbusChatBean();         //Eventbus传递所用实体类

    public static ChatActivity getInstance() {
        return chatActivity;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initWidget();
    }

    private void initWidget() {
        chatActivity = this;
        tivClassMore.setVisibility(View.VISIBLE);
        tvClassName.setVisibility(View.VISIBLE);
        Remarks = getIntent().getStringExtra("friendremarks") == null || getIntent().getStringExtra("friendremarks").equals("") ?
                getIntent().getStringExtra("nickname") : getIntent().getStringExtra("friendremarks");
        tvClassName.setText(Remarks);
        EMClient.getInstance().chatManager().addMessageListener(msgListener);
        fragments = new ArrayList<>();
        chatEmotionFragment = new ChatEmotionFragment();
        fragments.add(chatEmotionFragment);
        chatFunctionFragment = new ChatFunctionFragment();
        fragments.add(chatFunctionFragment);
        adapter = new CommonFragmentPagerAdapter(getSupportFragmentManager(), fragments);
        viewpager.setAdapter(adapter);
        viewpager.setCurrentItem(0);
        msgBeanDao = BaseApplication.getInstances().getDaoSession().getMsgBeanDao();
        isPushBeanDao = BaseApplication.getInstances().getDaoSession().getIsPushBeanDao();
        msgBeanList.clear();
        pushBean = isPushBeanDao.queryBuilder().where(IsPushBeanDao.Properties.ChatMsgId.
                eq(StaticValues.username + "#" +
                        getIntent().getStringExtra("username"))).unique();
        if (pushBean == null) {
            ivChat.setImageResource(R.color.bg_content);
        } else {
            if (pushBean.getBgpath() != null && !pushBean.getBgpath().equals("")) {
                Glide.with(this).load(pushBean.getBgpath()).into(ivChat);
            } else {
                ivChat.setImageResource(R.color.bg_content);
            }
        }

        mDetector = EmotionInputDetector.with(this)
                .setEmotionView(emotionLayout)
                .setViewPager(viewpager)
                .bindToContent(chatList)
                .bindToEditText(editText)
                .bindToEmotionButton(emotionButton)
                .bindToAddButton(emotionAdd)
                .bindToSendButton(emotionSend)
                .bindToVoiceButton(emotionVoice)
                .bindToVoiceText(voiceText)
                .build();

        GlobalOnItemClickManagerUtils globalOnItemClickListener = GlobalOnItemClickManagerUtils.getInstance(this);
        globalOnItemClickListener.attachToEditText(editText);

        chatAdapter = new ChatAdapter(this);
        layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        chatList.setLayoutManager(layoutManager);
        chatList.setAdapter(chatAdapter);
        chatList.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                switch (newState) {
                    case RecyclerView.SCROLL_STATE_IDLE:
                        chatAdapter.handler.removeCallbacksAndMessages(null);
                        chatAdapter.notifyDataSetChanged();
                        break;
                    case RecyclerView.SCROLL_STATE_DRAGGING:
                        chatAdapter.handler.removeCallbacksAndMessages(null);
                        mDetector.hideEmotionLayout(false);
                        mDetector.hideSoftInput();
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });

        chatList.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                if (bottom < oldBottom) {
                    chatList.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            chatList.scrollToPosition(chatAdapter.getAllData().size() - 1);
                        }
                    }, 100);
                }
            }
        });

        chatAdapter.addItemClickListener(itemClickListener);
        LoadData();
    }

    /**
     * 构造发送数据
     *
     * @param messageInfo
     * @param msgBean
     */
    private void SendDataInit(MessageInfo messageInfo, MsgBean msgBean) {
        if (messageInfo.getContent() != null && !messageInfo.getContent().equals("")) {
            message = EMMessage.createTxtSendMessage(messageInfo.getContent(), getIntent().getStringExtra("username"));
            msgBean.setMsgContent(messageInfo.getContent());
        } else if (messageInfo.getVideoUrl() != null && messageInfo.getImageUrl() != null &&
                !messageInfo.getVideoUrl().equals("") && !messageInfo.getImageUrl().equals("")) {
            message = EMMessage.createVideoSendMessage(messageInfo.getVideoUrl(), messageInfo.getImageUrl(),
                    messageInfo.getVideotime(),
                    getIntent().getStringExtra("username"));
            msgBean.setMsgContent(messageInfo.getVideoUrl());
            msgBean.setImgurl(messageInfo.getImageUrl());
        } else if (messageInfo.getImageUrl() != null && !messageInfo.getImageUrl().equals("")) {
            //imagePath为图片本地路径，false为不发送原图（默认超过100k的图片会压缩后发给对方），需要发送原图传true
            message = EMMessage.createImageSendMessage(messageInfo.getImageUrl(), false, getIntent().getStringExtra("username"));
            msgBean.setMsgContent(messageInfo.getImageUrl());
        } else if (messageInfo.getFilepath() != null && !messageInfo.getFilepath().equals("")) {
            MediaPlayer mediaPlayer = new MediaPlayer();
            try {
                mediaPlayer.setDataSource(messageInfo.getFilepath());
                mediaPlayer.prepare();
                message = EMMessage.createVoiceSendMessage(messageInfo.getFilepath(),
                        mediaPlayer.getDuration() / 1000,
                        getIntent().getStringExtra("username"));
            } catch (IOException e) {
                e.printStackTrace();
            }
            msgBean.setMsgContent(messageInfo.getFilepath());
        }
    }

    /**
     * 监听发送状态
     *
     * @param messageInfo
     * @param msgBean
     * @param s
     */
    private void SendLisenter(final MessageInfo messageInfo, final MsgBean msgBean, final int s) {
        message.setMessageStatusCallback(new EMCallBack() {
            @Override
            public void onSuccess() {
                if (eventlist == null) {
                    eventlist = new ArrayList<>();
                }
                eventbusChatBean.setFrom(StaticValues.username);
                eventbusChatBean.setMsgid("");
                eventlist.add(eventbusChatBean);
                msgBean.setId(null);
                msgBean.setChatMsgId(StaticValues.username + "#" + getIntent().getStringExtra("username"));
                msgBean.setMsgFrom(StaticValues.username);
                msgBean.setMsgTo(getIntent().getStringExtra("username"));
                msgBean.setMsgFromHead(StaticValues.userhead);
                msgBean.setMsgToHead(getIntent().getStringExtra("userhead"));
                msgBean.setMsgId("");
                msgBean.setMsgTime(System.currentTimeMillis());
                msgBeanDao.insert(msgBean);

                messageInfo.setSendState(Constants.CHAT_ITEM_SEND_SUCCESS);
                chatAdapter.notifyItemChanged(s);
            }

            @Override
            public void onError(int code, String error) {
                messageInfo.setSendState(Constants.CHAT_ITEM_SEND_ERROR);
                chatAdapter.notifyItemChanged(s);
            }

            @Override
            public void onProgress(int progress, String status) {
                messageInfo.setSendState(Constants.CHAT_ITEM_SENDING);
                chatAdapter.notifyItemChanged(s);
            }
        });
    }

    /**
     * 构造聊天数据
     */
    private void LoadData() {
        if (getIntent().getIntExtra("UnreadMsgCount", -1) == 0) {
            try {
                messageInfos = new ArrayList<>();
                msgBeanList = msgBeanDao.loadAll();
                MessageInfo messageInfo = null;
                List<MsgBean> morelist = new ArrayList<>();
                for (int i = 0; i < msgBeanList.size(); i++) {
                    if (msgBeanList.get(i).getChatMsgId().equals(StaticValues.username + "#" + getIntent().getStringExtra("username"))) {
                        if (!msgBeanList.get(i).getMsgId().equals("")) {
                            if (msgBeanList.get(i).getMsgFrom().equals(getIntent().getStringExtra("username"))) {
                                morelist.add(msgBeanList.get(i));
                            }
                        } else {
                            morelist.add(msgBeanList.get(i));
                        }
                    }
                }
                try {
                    if (!getIntent().getStringExtra("msg").
                            contains(morelist.get(morelist.size() - 1).getMsgContent())) {
                        messageInfos = new ArrayList<>();
                        getMsgList();
                        return;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                for (int i = 0; i < morelist.size(); i++) {
                    messageInfo = new MessageInfo();
                    if (morelist.get(i).getChatMsgId().equals(StaticValues.username + "#" + getIntent().getStringExtra("username"))) {
                        if (morelist.get(i).getMsgFrom().equals(StaticValues.username)) {
                            messageInfo.setHeader(StaticValues.userhead);
                            messageInfo.setType(Constants.CHAT_ITEM_TYPE_RIGHT);
                            messageInfo.setSendState(Constants.CHAT_ITEM_SEND_SUCCESS);
                            if (morelist.get(i).getMsgContent().contains("wav")) {
                                messageInfo.setFilepath(morelist.get(i).getMsgContent());
                            } else if (morelist.get(i).getMsgContent().contains("mp4")) {
                                messageInfo.setVideoUrl(morelist.get(i).getMsgContent());
                                messageInfo.setImageUrl(morelist.get(i).getImgurl());
                            } else if (morelist.get(i).getMsgContent().contains("jpg") ||
                                    morelist.get(i).getMsgContent().contains("png")) {
                                messageInfo.setImageUrl(morelist.get(i).getMsgContent());
                            } else {
                                messageInfo.setContent(morelist.get(i).getMsgContent());
                            }
                        } else {
                            messageInfo.setType(Constants.CHAT_ITEM_TYPE_LEFT);
                            messageInfo.setHeader(getIntent().getStringExtra("userhead"));
                            if (morelist.get(i).getMsgContent().startsWith("txt")) {
                                messageInfo.setContent(morelist.get(i).getMsgContent().substring(5,
                                        morelist.get(i).getMsgContent().length() - 1));
                            } else if (morelist.get(i).getMsgContent().startsWith("image")) {
                                messageInfo.setImageUrl(morelist.get(i).getMsgContent().split(",")[2]
                                        .split(",")[0].split("remoteurl:")[1]);
                            } else if (morelist.get(i).getMsgContent().startsWith("video")) {
                                messageInfo.setImageUrl(morelist.get(i).getMsgContent().split(",")[3]
                                        .split("thumbnailUrl:")[1]);
                                messageInfo.setVideoUrl(morelist.get(i).getMsgContent().split(",")[2]
                                        .split(",")[0].split("remoteUrl:")[1]);
                            } else if (morelist.get(i).getMsgContent().startsWith("voice")) {
                                messageInfo.setFilepath(morelist.get(i).getMsgContent().split(",")[2].
                                        split("remoteurl:")[1].split(",")[0]);
                                messageInfo.setVoiceTime(Integer.decode(morelist.get(i).getMsgContent().split("length:")[1]) * 1000);
                            }
                        }
                        messageInfos.add(messageInfo);
                        chatAdapter.add(messageInfo);
                    }
                }
                chatList.scrollToPosition(chatAdapter.getCount() - 1);
            } catch (Exception e) {
                messageInfos = new ArrayList<>();
                getMsgList();
            }
        } else {
            messageInfos = new ArrayList<>();
            getMsgList();
        }
    }

    /**
     * 在环信服务器获取最新20条数据
     */
    private void getMsgList() {
        if (messages != null) {
            messages.clear();
        }
        if (msglist != null) {
            msglist.clear();
        }
        if (eventlist != null) {
            eventlist.clear();
        } else {
            eventlist = new ArrayList<>();
        }
        EMConversation conversation = EMClient.getInstance().chatManager().getConversation(getIntent().getStringExtra("username"));
        try {
            //获取此会话的所有消息
            messages = conversation.getAllMessages();
            //SDK初始化加载的聊天记录为20条，到顶时需要去DB里获取更多
            //获取startMsgId之前的pagesize条消息，此方法获取的messages SDK会自动存入到此会话中，APP中无需再次把获取到的messages添加到会话中
            msglist = conversation.loadMoreMsgFromDB(messages.get(messages.size() - 1).getMsgId(),
                    getIntent().getIntExtra("UnreadMsgCount", 0));
            msglist.clear();
            Collections.reverse(messages);
            for (int i = 0; i < getIntent().getIntExtra("UnreadMsgCount", 0); i++) {
                msglist.add(messages.get(i));
            }
//            msglist.add(messages.get(messages.size() - getIntent().getIntExtra("UnreadMsgCount", 0)));
            List<MsgBean> msgBeanList = msgBeanDao.loadAll();
            for (int i = 0; i < msgBeanList.size(); i++) {
                if ((StaticValues.username + "#" + getIntent().getStringExtra("username"))
                        .equals(msgBeanList.get(i).getChatMsgId())) {
                    MessageInfo messageInfo = null;
                    if (msgBeanList.get(i).getMsgFrom().equals(StaticValues.username)) {
                        messageInfo = new MessageInfo();
                        messageInfo.setHeader(StaticValues.userhead);
                        messageInfo.setType(Constants.CHAT_ITEM_TYPE_RIGHT);
                        messageInfo.setSendState(Constants.CHAT_ITEM_SEND_SUCCESS);
                        if (msgBeanList.get(i).getMsgContent().contains("wav")) {
                            messageInfo.setFilepath(msgBeanList.get(i).getMsgContent());
                        } else if (msgBeanList.get(i).getMsgContent().contains("mp4")) {
                            messageInfo.setVideoUrl(msgBeanList.get(i).getMsgContent());
                            messageInfo.setImageUrl(msgBeanList.get(i).getImgurl());
                        } else if (msgBeanList.get(i).getMsgContent().contains("jpg") ||
                                msgBeanList.get(i).getMsgContent().contains("png")) {
                            messageInfo.setImageUrl(msgBeanList.get(i).getMsgContent());
                        } else {
                            messageInfo.setContent(msgBeanList.get(i).getMsgContent());
                        }
                    } else {
                        messageInfo = new MessageInfo();
                        messageInfo.setType(Constants.CHAT_ITEM_TYPE_LEFT);
                        messageInfo.setHeader(getIntent().getStringExtra("userhead"));
                        if (msgBeanList.get(i).getMsgContent().startsWith("txt")) {
                            messageInfo.setContent(msgBeanList.get(i).getMsgContent().substring(5,
                                    msgBeanList.get(i).getMsgContent().length() - 1));
                        } else if (msgBeanList.get(i).getMsgContent().startsWith("image")) {
                            messageInfo.setImageUrl(msgBeanList.get(i).getMsgContent().split(",")[2]
                                    .split(",")[0].split("remoteurl:")[1]);
                        } else if (msgBeanList.get(i).getMsgContent().startsWith("video")) {
                            messageInfo.setImageUrl(msgBeanList.get(i).getMsgContent().split(",")[3]
                                    .split("thumbnailUrl:")[1]);
                            messageInfo.setVideoUrl(msgBeanList.get(i).getMsgContent().split(",")[2]
                                    .split(",")[0].split("remoteUrl:")[1]);
                        } else if (msgBeanList.get(i).getMsgContent().startsWith("voice")) {
                            messageInfo.setFilepath(msgBeanList.get(i).getMsgContent().split(",")[2].
                                    split("remoteurl:")[1].split(",")[0]);
                            messageInfo.setVoiceTime(Integer.decode(msgBeanList.get(i).getMsgContent().split("length:")[1]) * 1000);
                        }
                    }
                    messageInfos.add(messageInfo);
                    chatAdapter.add(messageInfo);
                }
            }
            for (int i = 0; i < msglist.size(); i++) {
                addMsgData(msglist, i, false);
                eventbusChatBean.setFrom(messages.get(i).getFrom());
                eventbusChatBean.setMsgid(messages.get(i).getMsgId());
                eventlist.add(eventbusChatBean);
            }
            int s = chatAdapter.getCount() - 1;
            chatList.scrollToPosition(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onBackPressed() {
        if (!mDetector.interceptBackPress()) {
            super.onBackPressed();
        }
    }

    /**
     * 构造聊天数据
     *
     * @param messages
     * @param i
     * @param b
     */
    private void addMsgData(final List<EMMessage> messages, final int i, boolean b) {
        try {
            MessageInfo message = new MessageInfo();
            MsgBean msgBean = new MsgBean();
            if (messages.get(i).getBody().toString().startsWith("txt")) {
                message.setContent(messages.get(i).getBody().toString().substring(5,
                        messages.get(i).getBody().toString().length() - 1));
            } else if (messages.get(i).getBody().toString().startsWith("image")) {
                message.setImageUrl(messages.get(i).getBody().toString().split(",")[2]
                        .split(",")[0].split("remoteurl:")[1]);
            } else if (messages.get(i).getBody().toString().startsWith("video")) {
                message.setImageUrl(messages.get(i).getBody().toString().split(",")[3]
                        .split("thumbnailUrl:")[1]);
                message.setVideoUrl(messages.get(i).getBody().toString().split(",")[2]
                        .split(",")[0].split("remoteUrl:")[1]);
                msgBean.setImgurl(messages.get(i).getBody().toString().split(",")[3]
                        .split("thumbnailUrl:")[1]);
            } else if (messages.get(i).getBody().toString().startsWith("voice")) {
                message.setFilepath(messages.get(i).getBody().toString().split(",")[2].
                        split("remoteurl:")[1].split(",")[0]);
                message.setVoiceTime(Integer.decode(messages.get(i).getBody().toString().split("length:")[1]) * 1000);
            }
            if (b) {
                message.setType(Constants.CHAT_ITEM_TYPE_LEFT);
                message.setHeader(getIntent().getStringExtra("userhead"));
            } else {
                if (msglist.get(i).getFrom().equals(StaticValues.username)) {
                    message.setType(Constants.CHAT_ITEM_TYPE_RIGHT);
                    message.setHeader(StaticValues.userhead);
                } else {
                    message.setType(Constants.CHAT_ITEM_TYPE_LEFT);
                    message.setHeader(getIntent().getStringExtra("userhead"));
                }
            }
            msgBean.setId(null);
            msgBean.setChatMsgId(StaticValues.username + "#" + messages.get(i).getFrom());
            msgBean.setMsgId(messages.get(i).getMsgId());
            msgBean.setMsgFrom(messages.get(i).getFrom());
            msgBean.setMsgTo(messages.get(i).getTo());
            msgBean.setMsgFromHead(getIntent().getStringExtra("userhead"));
            msgBean.setMsgTo(StaticValues.userhead);
            msgBean.setMsgContent(messages.get(i).getBody().toString());
            msgBean.setMsgTime(messages.get(i).getMsgTime());
            msgBeanDao.insert(msgBean);
            if (messages.get(i).getFrom().equals(getIntent().getStringExtra("username"))) {
                chatAdapter.add(message);
                messageInfos.add(message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        StaticValues.ispush = true;
        if (eventlist != null) {
            EventBus.getDefault().post(eventlist);
        }
        EventBus.getDefault().removeStickyEvent(this);
        EventBus.getDefault().unregister(this);
        EMClient.getInstance().chatManager().removeMessageListener(msgListener);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void ChatMessageEventBus(List<EMMessage> messages) {
        for (int i = 0; i < messages.size(); i++) {
            addMsgData(messages, i, true);
        }
        //收到消息
        int s = chatAdapter.getCount() - 1;
        chatList.scrollToPosition(s);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void DleteEventBus(MessageEvent messages) {
        if (messages.getMessage().contains("删除聊天记录")) {
            chatAdapter.clear();
            messageInfos.clear();
        } else if (messages.getMessage().equals("修改背景")) {
            pushBean = isPushBeanDao.queryBuilder().where(IsPushBeanDao.Properties.ChatMsgId.
                    eq(StaticValues.username + "#" +
                            getIntent().getStringExtra("username"))).unique();
            if (pushBean == null) {
                ivChat.setImageResource(R.color.bg_content);
            } else {
                if (pushBean.getBgpath() != null && !pushBean.getBgpath().equals("")) {
                    Glide.with(this).load(pushBean.getBgpath()).into(ivChat);
                } else {
                    ivChat.setImageResource(R.color.bg_content);
                }
            }
        } else if (messages.getMessage().startsWith("备注:")) {
            Remarks = messages.getMessage().split("备注:")[1];
            tvClassName.setText(Remarks);
        }
    }

    /**
     * eventbus监听
     *
     * @param messageInfo
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void MessageEventBus(final MessageInfo messageInfo) {
        final MsgBean msgBean = new MsgBean();
        messageInfo.setHeader(StaticValues.userhead);
        messageInfo.setSendState(Constants.CHAT_ITEM_SENDING);
        messageInfo.setType(Constants.CHAT_ITEM_TYPE_RIGHT);
        chatList.scrollToPosition(chatAdapter.getCount() - 1);
        SendDataInit(messageInfo, msgBean);
        if (eventlist == null) {
            eventlist = new ArrayList<>();
        }
        eventbusChatBean.setFrom(StaticValues.username);
        eventbusChatBean.setMsgid("");
        eventlist.add(eventbusChatBean);
        EMClient.getInstance().chatManager().sendMessage(message);
        messageInfos.add(messageInfo);
        chatAdapter.add(messageInfo);
        //收到消息
        final int s = chatAdapter.getCount() - 1;
        chatList.scrollToPosition(s);
        SendLisenter(messageInfo, msgBean, s);
    }

    /**
     * 监听消息
     */
    EMMessageListener msgListener = new EMMessageListener() {

        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            if (eventlist == null) {
                eventlist = new ArrayList<>();
            }
            for (int i = 0; i < messages.size(); i++) {
                eventbusChatBean.setFrom(messages.get(i).getFrom());
                eventbusChatBean.setMsgid(messages.get(i).getMsgId());
                eventlist.add(eventbusChatBean);
                if (!messages.get(i).getFrom().equals(getIntent().getStringExtra("username"))) {
                    StaticValues.ispush = true;
                } else {
                    StaticValues.ispush = false;
                }
            }
            EventBus.getDefault().post(messages);
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {
            //收到透传消息
        }

        @Override
        public void onMessageRead(List<EMMessage> messages) {
            //收到已读回执
        }

        @Override
        public void onMessageDelivered(List<EMMessage> message) {
            //收到已送达回执
            System.out.println(message);
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
            //消息状态变动
        }
    };

    /**
     * item点击事件
     */
    private ChatAdapter.onItemClickListener itemClickListener = new ChatAdapter.onItemClickListener() {
        @Override
        public void onHeaderClick(int position) {
            Intent intent = new Intent();
            intent.putExtra("type", messageInfos.get(position).getType());
            if (messageInfos.get(position).getType() == Constants.CHAT_ITEM_TYPE_RIGHT) {
                intent.putExtra("id", StaticValues.userid);
                intent.putExtra("nickname", StaticValues.nickname);
                intent.putExtra("userhead", StaticValues.userhead);
                intent.putExtra("username", StaticValues.username);
            } else {
                intent.putExtra("id", getIntent().getIntExtra("id", 0));
                intent.putExtra("nickname", getIntent().getStringExtra("nickname"));
                intent.putExtra("userhead", getIntent().getStringExtra("userhead"));
                intent.putExtra("username", getIntent().getStringExtra("username"));
                intent.putExtra("friendremarks", Remarks == null || Remarks.equals("") ?
                        "" : Remarks);
            }
            intent.setClass(ChatActivity.this, FriendDetailActivity.class);
            startActivity(intent);
        }

        @Override
        public void onImageClick(View view, int position) {
            int location[] = new int[2];
            view.getLocationOnScreen(location);
            FullImageInfo fullImageInfo = new FullImageInfo();
            fullImageInfo.setLocationX(location[0]);
            fullImageInfo.setLocationY(location[1]);
            fullImageInfo.setWidth(view.getWidth());
            fullImageInfo.setHeight(view.getHeight());
            fullImageInfo.setImageUrl(messageInfos.get(position).getImageUrl());
            EventBus.getDefault().postSticky(fullImageInfo);
            if (messageInfos.get(position).getVideoUrl() != null && !messageInfos.get(position).getVideoUrl().equals("")) {
                Intent intent = new Intent();
                intent.putExtra("url", messageInfos.get(position).getVideoUrl());
                intent.setClass(ChatActivity.this, VideoActivity.class);
                startActivity(intent);
            } else {
                startActivity(new Intent(ChatActivity.this, FullImageActivity.class));
            }
            overridePendingTransition(0, 0);
        }

        @Override
        public void onVoiceClick(final ImageView imageView, final int position) {
            if (animView != null) {
                animView.setImageResource(res);
                animView = null;
            }
            switch (messageInfos.get(position).getType()) {
                case 1:
                    animationRes = R.drawable.voice_left;
                    res = R.mipmap.icon_voice_left3;
                    break;
                case 2:
                    animationRes = R.drawable.voice_right;
                    res = R.mipmap.icon_voice_right3;
                    break;
            }
            animView = imageView;
            animView.setImageResource(animationRes);
            animationDrawable = (AnimationDrawable) imageView.getDrawable();
            animationDrawable.start();
            MediaManager.playSound(messageInfos.get(position).getFilepath(), new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    animView.setImageResource(res);
                }
            });
        }

        @Override
        public void onMsgClick(View v, int position) {
            if (messageInfos.get(position).getType() == Constants.CHAT_ITEM_TYPE_RIGHT) {
                if (messageInfos.get(position).getSendState() == Constants.CHAT_ITEM_SEND_ERROR) {
                    final MsgBean msgBean = new MsgBean();
                    SendDataInit(messageInfos.get(position), msgBean);
                    EMClient.getInstance().chatManager().sendMessage(message);
                    SendLisenter(messageInfos.get(position), msgBean, chatAdapter.getCount() - 1);
                }
            }
        }
    };

    @OnClick({R.id.iv_class_back, R.id.tiv_class_more})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_class_back:
                finish();
                break;
            case R.id.tiv_class_more:
                Intent intent = new Intent();
                intent.putExtra("id", getIntent().getIntExtra("id", 0));
                intent.putExtra("nickname", getIntent().getStringExtra("nickname"));
                intent.putExtra("userhead", getIntent().getStringExtra("userhead"));
                intent.putExtra("username", getIntent().getStringExtra("username"));
                intent.putExtra("friendremarks", Remarks == null || Remarks.equals("") ?
                        "" : Remarks);
                intent.setClass(this, ChatSettingsActivity.class);
                startActivity(intent);
                break;
        }
    }
}
